package com.momo.upms.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.momo.common.core.request.PageParams;
import com.momo.common.core.result.Rs;
import com.momo.upms.condition.UserCondition;
import com.momo.upms.dto.UserDTO;
import com.momo.upms.entity.User;
import com.momo.upms.mapper.UserMapper;
import com.momo.upms.service.UserService;
import com.momo.upms.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Rs<Page<UserVO>> pageUser(PageParams<UserCondition> userCondition) {
        log.info("用户 分页查询");
        UserCondition model = userCondition.getModel();
        Page<UserVO> page = baseMapper.selectPage(userCondition.getPage(), Wrappers.lambdaQuery(User.class)
                .like(StringUtils.isNotBlank(model.getUsername()),User::getUsername, model.getUsername()));
        return Rs.success(page);
    }

    @Override
    public Rs<UserVO> insertUser(UserDTO userDTO) {
        userDTO.setPassword(BCrypt.hashpw(userDTO.getPassword(), BCrypt.gensalt()));
        User user = new User();
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userDTO, user);
        baseMapper.insert(user);
        BeanUtils.copyProperties(user, userVO);
        return Rs.success(userVO);
    }

    @Override
    public Rs<UserVO> updateUser(UserDTO userDTO) {
        User user = new User();
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userDTO, user);
        baseMapper.updateById(user);
        BeanUtils.copyProperties(user, userVO);
        return Rs.success(userVO);
    }

    @Override
    public Rs<UserVO> getUser(Long userId) {
        UserVO userVO = new UserVO();
        User user = baseMapper.selectById(userId);
        BeanUtils.copyProperties(user, userVO);
        return Rs.success(userVO);
    }

    @Override
    public Rs<Boolean> deleteUser(Long userId) {
        if (userId == 4L){
            return Rs.fail("users为超级管理员，无法删除。");
        }
        int delete = baseMapper.deleteById(userId);
        return Rs.success(SqlHelper.retBool(delete));
    }

}
